package com.AuthServer.config.interceptor;

import com.AuthServer.pojo.entity.Perm;
import com.AuthServer.pojo.entity.User;
import com.AuthServer.service.SecretService;
import com.AuthServer.utils.JsonUtil;
import com.AuthServer.utils.JwtUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;

public class TokenInterceptor implements RequestInterceptor {

    @Autowired
    @Qualifier("default")
    private RedisTemplate<String,Object> template;
    @Autowired
    private SecretService secretService;

    @SneakyThrows
    @Override
    public void apply(RequestTemplate requestTemplate) {
        String voidUserInfo_key = "user_0000000000";
        String voidUserInfo = (String) template.opsForValue().get(voidUserInfo_key);
        if (voidUserInfo == null){
            voidUserInit(voidUserInfo_key, template);
            requestTemplate.header("Authorization",JwtUtil.createJwt(voidUserInfo_key,template,secretService));
        } else {
            requestTemplate.header("Authorization",JwtUtil.createJwt(voidUserInfo_key,template,secretService));
        }
    }

    private static void voidUserInit(String voidUserInfo_key, RedisTemplate<String, Object> template) throws JsonProcessingException {
        User voidUser = new User();
        Perm perm = new Perm();
        perm.setPermDetail("void_user");
        voidUser.setUserId("0000000000");
        voidUser.getPermList().add(perm);
        String voidUserInfo = JsonUtil.serialize(voidUser);
        template.opsForValue().set(voidUserInfo_key,voidUserInfo);
    }
}
